﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace SharingCenter.Web.Services
{
    using SharingCenter.Web.Classes;
    using SharingCenter.Web.Classes.Groups;
    using SharingCenter.Web.Classes.enums;
    using System.Xml.Linq;
    using SharingCenter.Web.Classes.Requests;
    /// <summary>
    /// Summary description for GroupServices
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class GroupServices : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod]
        public bool GroupExists(string groupName)
        {
            return Convert.ToBoolean(scDataContext.Instance.GroupExists(groupName));
        }

        [WebMethod]
        [ScriptMethod]
        public bool OtherGroupExists(string groupName, string thisGroupId)
        {
            Guid gid;
            try { gid = new Guid(thisGroupId); }
            catch { return true; }
            return Convert.ToBoolean(scDataContext.Instance.OtherGroupExists(groupName, gid));
        }

        [WebMethod]
        [ScriptMethod]
        public bool AddUserToGroup(string groupid, string userid)
        {
            Guid gid, uid;
            try
            {
                gid = new Guid(groupid);
                uid = new Guid(userid);
            }
            catch { return false; }

            GroupOperations.AddUserToGroup(uid, gid, true);
            GroupOperations.AddSiteEventOnNewMember(gid, uid);
            return true;
        }

        [WebMethod]
        [ScriptMethod]
        public bool JoinGroupRequest(string groupId, string groupName, string comment, string userId)
        {
            Guid gid, uid;
            try
            {
                gid = new Guid(groupId);
                uid = new Guid(userId);
            }
            catch { return false; }

            List<Guid> admin = GroupOperations.GetGroupAdminUserList(gid);
            XElement context = new XElement("GroupRequestContext",
               new XAttribute("XsltFolderInMod", "Groups"),
               new XElement("GroupId", groupId),
               new XElement("RequestorUserId", userId),
               new XElement("GroupName", groupName),
               new XElement("Comment", comment)
               );
            Sc_SharedRequest r = RequestOperations.AddRequest(EntityType.Group, gid, uid, admin, context);
            return r != null;
        }
    }
}
